﻿using LogSystem;
using UnityEngine;
using UnityEngine.UI;
using Yoozoo.Core.Common;

public class LinkRenderTexture : MonoBehaviour
{
    public RawImage targetImage;
    public Camera renderCamera;
    public RectTransform actorRoot;
    public int width, height;
    public int virtualWidth = 1334, virtualHeight = 750;
    public float scaleRatio = 1f;
    RenderTexture tempRt;

    private void Awake()
    {
        var qualityManager = QualityManager.Inst;
        if (qualityManager != null && qualityManager.currentAdjusterSetting != null)
        {
            var currentAdjusterSetting = qualityManager.currentAdjusterSetting;
            scaleRatio = currentAdjusterSetting.resolutionPercent / 100;
            Debug.LogFormat(LogModule.Commander, "当前质量: {0}, 当前分辨率百分比: {1}%",
                qualityManager.CurrentQuality, currentAdjusterSetting.resolutionPercent);

            var descriptor = new RenderTextureDescriptor((int)(width * scaleRatio), (int)(height * scaleRatio));
            descriptor.useMipMap = false;
            descriptor.enableRandomWrite = false;
            descriptor.depthBufferBits = 0;
            descriptor.autoGenerateMips = false;
            descriptor.memoryless = RenderTextureMemoryless.None;
            descriptor.colorFormat = RenderTextureFormat.DefaultHDR;
            tempRt = RenderTexture.GetTemporary(descriptor);
            if (renderCamera != null)
            {
                renderCamera.targetTexture = tempRt;
            }
            if (targetImage != null)
            {
                targetImage.texture = tempRt;
            }
        }
       
    }

    private void Start()
    {
        OnRatioChange();
    }

#if UNITY_EDITOR
    private void Update()
    {
        OnRatioChange();
    }
#endif

    private void OnDestroy()
    {
        if (tempRt)
        {
            RenderTexture.ReleaseTemporary(tempRt);
        }
        
    }

    private void OnRatioChange()
    {
        int ScreenWidth = Screen.width;
        int ScreenHeight = Screen.height;
        float ratio = 1f,ratio2 = 1f;
        //屏幕比率,宽度优先,因为英雄名字和banner会在屏幕上
        float ratioScreen = ScreenWidth / ScreenHeight;
        ratio = 1.0f * ScreenWidth / virtualWidth;//Mathf.Max(, 1.0f * ScreenHeight / virtualHeight);
        bool heightOverflow = (ratio*virtualHeight) < ScreenHeight;
        if (heightOverflow)
        {
            ratio2 = ScreenHeight / (ratio * virtualHeight); 
        }

        ratio = ratio * ratio2;
        
        //二次限制,倘若横向角色超过屏幕太多,就按照原本的防止匹配,保证宽度优先
        if (((ratio * virtualWidth) - ScreenWidth) > virtualWidth*0.4f)
        {
            ratio =  1.0f * ScreenWidth / virtualWidth;
        }
        
        actorRoot.localScale = new Vector3(ratio, ratio, ratio);
    }
}
